package com.netted.operationassistant.activity;

import android.app.ProgressDialog;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.android.volley.VolleyError;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.netted.operationassistant.R;
import com.netted.operationassistant.constant.Constant;
import com.netted.operationassistant.http.HttpRequest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BindCatbinetActivity extends BaseActivity {
    private TextView catbinet_code;
    private TextView catbinet_name;
    private TextView catbinet_count;
    private Spinner shengSpinner;
    private Spinner citySpinner;
    private Spinner schoolSpinner;
    private Spinner catbinetSpinner;


    private JSONArray areaJsonArr = null;
    private JSONArray cityJsonArr = null;
    private JSONArray schoolJsonArr = null;
    private int portCount = 0;

    public String catbinetId;
    public String catbinetCode;
    public String catbinetName;
    public String schoolId;
    public String catbinetPortCount;
    public String schoolAreaId;
    public String schoolName;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_catbinet);
        catbinet_code = (TextView)findViewById(R.id.bindCatbinet_catbinet_code);
        catbinet_name = (TextView)findViewById(R.id.bindCatbinet_catbinet_name);
        catbinet_count = (TextView)findViewById(R.id.bindCatbinet_catbinet_count);

        shengSpinner = (Spinner)findViewById(R.id.bindCatbinet_sheng_spinner);
        citySpinner = (Spinner)findViewById(R.id.bindCatbinet_city_spinner);
        schoolSpinner = (Spinner)findViewById(R.id.bindCatbinet_school_spinner);
        catbinetSpinner = (Spinner)findViewById(R.id.bindCatbinet_catbinet_spinner);
        showArea();
    }


    //显示可选地区和学校
    public void showArea(){
        if("".equals(Constant.AREA_JSON) || null == Constant.AREA_JSON){
            return;
        }
        areaJsonArr = JSONArray.parseArray(Constant.AREA_JSON);
        if (areaJsonArr.size() > 0){
            List<String> sList = new ArrayList<>(areaJsonArr.size());
            for(int i = 0; i < areaJsonArr.size(); i ++){

                sList.add( areaJsonArr.getJSONObject(i).getString("name"));

            }
            ArrayAdapter<String> shengAdapter = new ArrayAdapter<String>(this,R.layout.spinner_item,sList);
            shengSpinner.setAdapter(shengAdapter);
        }

        shengSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                citySpinner.setAdapter(null);
                schoolSpinner.setAdapter(null);
                catbinetSpinner.setAdapter(null);
                catbinet_code.setText("");
                catbinet_name.setText("");
                catbinet_count.setText("");
                JSONArray citys = areaJsonArr.getJSONObject(i).getJSONArray("citys");
                bindCitys(citys);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }


    private void bindCitys(JSONArray citys){
        cityJsonArr = citys;
        List<String> cityList = new ArrayList<>();
        if (citys != null && citys.size() > 0){
            for(int i = 0; i < citys.size(); i ++){
                cityList.add(citys.getJSONObject(i).getString("name"));
            }
        }
        ArrayAdapter<String> shengAdapter = new ArrayAdapter<String>(this,R.layout.spinner_item,cityList);
        citySpinner.setAdapter(shengAdapter);
        citySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String cityId = cityJsonArr.getJSONObject(i).getString("id");
                schoolSpinner.setAdapter(null);
                catbinetSpinner.setAdapter(null);
                catbinet_code.setText("");
                catbinet_name.setText("");
                catbinet_count.setText("");
                getSchool(cityId);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    public void getSchool(String id){
        final ProgressDialog progressDialog = ProgressDialog.show(this,"Loading...", "正在读取学校列表...", true, false);
        String url = Constant.HOST + "/ws/opt/getSchool";
        Map<String,String> params = new HashMap<>();

        params.put("area",id);

        request.post(url, params, "post", new HttpRequest.Callback() {
            @Override
            public void onSuccess(String response) {
                progressDialog.dismiss();
                if (response != null){
                    JSONObject json = JSONObject.parseObject(response);
                    if ("success".equals(json.getString("flag"))){
                        String data = json.getString("data");
                        if (data == null || "".equals(data) || "[]".equals(data)){

                            showDialog("提示","该地区无学校记录",null);
                            return;
                        }
                        JSONArray dataJsonArr = JSONArray.parseArray(data);

                        bindSchool(dataJsonArr);
                        return;
                    }
                }
                showDialog("提示","获取学校记录出错",null);
            }

            @Override
            public void onError(VolleyError error) {
                progressDialog.dismiss();
                showDialog("提示","获取学校记录出错",null);
            }
        });
    }


    private void bindSchool(JSONArray dataJsonArr){
        schoolJsonArr = dataJsonArr;
        schoolId = null;
        List<String> sList = new ArrayList<>();
        if (dataJsonArr != null && dataJsonArr.size() > 0){
            for(int i = 0; i < dataJsonArr.size(); i ++){
                sList.add(dataJsonArr.getJSONObject(i).getString("name"));
            }
        }else{
            return;
        }

        ArrayAdapter<String> shengAdapter = new ArrayAdapter<String>(this,R.layout.spinner_item,sList);
        schoolSpinner.setAdapter(shengAdapter);
        schoolSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                catbinetSpinner.setAdapter(null);
                catbinet_code.setText("");
                catbinet_name.setText("");
                catbinet_count.setText("");
                schoolId = schoolJsonArr.getJSONObject(i).getString("id");
                schoolName = schoolJsonArr.getJSONObject(i).getString("name");
                schoolAreaId = schoolJsonArr.getJSONObject(i).getString("area");
                String url = Constant.HOST + "/ws/opt/getFreeCatbinet";
                Map<String,String> params = new HashMap<>();
                params.put("schoolId",schoolId);
                request.post(url, params, "post", new HttpRequest.Callback() {
                    @Override
                    public void onSuccess(String response) {
                        JSONObject resJson = JSONObject.parseObject(response);
                        if("success".equals(resJson.getString("flag"))){
                            String datas = resJson.getString("data");
                            if (datas != null && datas.length() > 0){
                                JSONArray dataJsonArr = JSONArray.parseArray(datas);

                                bindCatbinet(dataJsonArr);
                            }
                        }
                    }

                    @Override
                    public void onError(VolleyError error) {

                    }
                });
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }


    private void bindCatbinet(final JSONArray dataJsonArr){
        catbinet_code.setText("");
        catbinet_name.setText("");
        catbinet_count.setText("");
        List<String> sList = new ArrayList<>();
        if (dataJsonArr != null && dataJsonArr.size() > 0){
            for(int i = 0; i < dataJsonArr.size(); i ++){
                sList.add(dataJsonArr.getJSONObject(i).getString("name"));
            }
        }


        ArrayAdapter<String> catbinetAdapter = new ArrayAdapter<String>(this,R.layout.spinner_item,sList);
        catbinetSpinner.setAdapter(catbinetAdapter);
        catbinetSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                catbinetId = dataJsonArr.getJSONObject(i).getString("id");
                catbinetName = dataJsonArr.getJSONObject(i).getString("name");
                catbinetCode = dataJsonArr.getJSONObject(i).getString("code");
                portCount = dataJsonArr.getJSONObject(i).getInteger("port");

                catbinet_code.setText(catbinetCode);
                catbinet_name.setText(catbinetName);
                catbinet_count.setText(portCount+"");





            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

    }

    public void exitActivity(View view){
        this.finish();
    }


    public void submit(View view){
        final ProgressDialog loadingDialog = ProgressDialog.show(this,"读取中", "正在验证信息", true, false);
        loadingDialog.show();
        String url = Constant.HOST + "/ws/opt/bindCatbinet";
        Map<String,String> params = new HashMap<>();
        params.put("catbinetId",catbinetId);
        request.post(url, params, "post", new HttpRequest.Callback() {
            @Override
            public void onSuccess(String response) {
                loadingDialog.dismiss();
                if (response != null){
                    JSONObject json = JSONObject.parseObject(response);
                    if ("success".equals(json.getString("flag"))){


                        getPort();
                        sharedPreferencesHelper.put(Constant.XML_CATBINET_ID,catbinetId);
                        sharedPreferencesHelper.put(Constant.XML_CATBINET_CODE,catbinetCode);
                        sharedPreferencesHelper.put(Constant.XML_CATBINET_NAME,catbinetName);
                        sharedPreferencesHelper.put(Constant.XML_SCHOOL_ID,schoolId);
                        sharedPreferencesHelper.put(Constant.XML_CATBINET_PORT_COUNT,portCount+"");
                        sharedPreferencesHelper.put(Constant.XML_SCHOOL_NAME,schoolName);
                        sharedPreferencesHelper.put(Constant.XML_SCHOOL_AREA_ID,schoolAreaId);
                        ToastUtils.showLong("操作成功");
                        BindCatbinetActivity.this.finish();
                        return;
                    }
                }
                showDialog("提示","绑定机柜数据出错",null);
            }

            @Override
            public void onError(VolleyError error) {

            }
        });
    }
    public void getPort(){
        final Handler handler = new Handler();
        new Thread(new Runnable() {
            @Override
            public void run() {
                int count = 0;
                for(int i = 0; i < 3; i ++){
                    getPortCount(  i);
                    try {
                        Thread.sleep(1000);
                        if (!"".equals(serialValue)){
                            boolean b = verify(serialValue);
                            if(b){
                                String[] arr = serialValue.split(" ");
                                sharedPreferencesHelper.put(Constant.XML_BROAD_ + i,Integer.parseInt(arr[arr.length - 3]));
                                count += Integer.parseInt(arr[arr.length - 3]);
                            }else{
//                    showDialog("提示","校验错误",null);
                            }
                        }else{
//                showDialog("提示","无应答,该板不存在!",null);
                        }
                        serialValue = "";
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                final int c = count;
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        catbinet_count.setText(c+"");
                    }
                });
            }
        }).start();


    }


}
